//
//  HomeTableViewController.swift
//  XKWeibo
//
//  Created by 小k on 15/11/4.
//  Copyright © 2015年 小k. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 原创微博cell 可重用标示
 let StatusCellNormalID = "StatusCellNormalID"
/// 转发微博 Cell 的可重用表示符号
let StatusCellRetweetedId = "StatusCellRetweetedId"


class HomeTableViewController: VisitorViewController {

    /// 微博数据模型数组
    private lazy var listViewModel = XKStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !XKUserAccountViewModel.sharedUserAccount.userLogin {
        visitorView?.setupInfo(nil, textName: "关注一些人，回这里看看有什么惊喜关注一些人，回这里看看有什么惊喜")
            return
        }
        
        prepareTableView()
        
        loadData()
    }
    
    /// 准备表格
    private func prepareTableView () {
        // 注册可重用cell
        tableView.registerClass(XKStatusNormalCell.self, forCellReuseIdentifier: StatusCellNormalID)
        tableView.registerClass(XKStatusRetweetedCell.self, forCellReuseIdentifier: StatusCellRetweetedId)
        
        // 取消分割线
        tableView.separatorStyle = .None
        
        // 预估行高
        tableView.estimatedRowHeight = 400
        
        /// 创建一个下拉刷新控件
        refreshControl = XKRefreshControl()
        
        /// 添加方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        /// 上拉刷新
        tableView.tableFooterView = pullupView
        
        // 测试行高
//        tableView.rowHeight = 300
    }
    
    // MARK: - 懒加载控件
    /// 下拉提示标签
    private lazy var pulldownTipLabel: UILabel = {
        
        let label = UILabel(title: "", titleColor: UIColor.orangeColor(), titleFont: 18)
        label.backgroundColor = UIColor.orangeColor()
        
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
        }()
    
    /// 上拉刷新提示视图
    private lazy var pullupView: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        indicator.color = UIColor.redColor()
        return indicator
        
    }()
    
    
    /// 加载数据
   @objc private func loadData() {
        // 开始刷新
        refreshControl?.beginRefreshing()
        
        listViewModel.loadStatus(isPullup: pullupView.isAnimating()) { (isSuccessed) -> () in
            
            // 关闭刷新
            self.refreshControl?.endRefreshing()
            // 关闭上拉刷新
            self.pullupView.stopAnimating()
            
            if !isSuccessed {
                SVProgressHUD.showErrorWithStatus("加载数据错误, 请稍后重试")
                return
            }
            
//            print(self.listViewModel.statusList)
            // 刷新数据
            self.tableView.reloadData()
        }
    }
    
    /// 显示下拉刷新提示
    private func showPulldownTip() {
        
        // 判断是否下拉刷新
        guard let count = listViewModel.pulldownCount else {
            return
        }
        
        let message = count > 0 ? "刷新到了 \(count) 条微博" : "没有刷新到数据"
        
        let height:CGFloat = 44
        let rect = CGRect(x: 0, y: -2 * height, width: view.bounds.width, height: height)
        
        pulldownTipLabel.text = message
        pulldownTipLabel.frame = rect
        
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            self.pulldownTipLabel.frame = CGRectOffset(rect, 0, 3 * height)
            }) { _ in
                UIView.animateWithDuration(1.0) { self.pulldownTipLabel.frame = rect }
        }
    }
}



// MARK: - 数据源方法
extension HomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print(listViewModel.statusList.count)
        return listViewModel.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 1. 获取视图模型
        let vm = listViewModel.statusList[indexPath.row]
        
        // 2. 获取可重用Cell
        let cell = tableView.dequeueReusableCellWithIdentifier(vm.cellId, forIndexPath: indexPath) as! XKStatusCell
        
        // 3. 设置视图模型
        cell.viewModle = vm
        
        // 4. 判断是否要下拉刷新
        if indexPath.row == listViewModel.statusList.count - 1 && !pullupView.isAnimating() {
            // 开始动画
            pullupView.startAnimating()
            
            // 刷新数据
            loadData()
            print("上拉刷新数据")
        }
        
        // 返回cell
        return cell
    }
    
    // 计算行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        return listViewModel.statusList[indexPath.row].rowHeight
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("选中行 \(indexPath)")
    }
    
    
}